package com.grsu.phonestation.dao.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.grsu.phonestation.dao.EnrolleePaymentDAO;
import com.grsu.phonestation.domain.EnrolleePayment;

@Repository
public class EnrolleePaymentDAOImpl extends
		PaymentDAOImpl<EnrolleePayment> implements EnrolleePaymentDAO {

	@Override
	protected Class<EnrolleePayment> getGenericEntityClass() {
		return (Class<EnrolleePayment>) EnrolleePayment.class;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public double getSumEnrolleePaymentClientForPeriod(String user,
			String beginPeriod, String endPeriod) {
		Criteria criteria = getSession().createCriteria(EnrolleePayment.class);
		if (user != null && !user.isEmpty()) {
			criteria.createAlias("payment.user", "user");
			criteria.add(Restrictions.or(Restrictions.like("user.firstName",
					user, MatchMode.ANYWHERE), Restrictions.like(
					"user.lastName", user, MatchMode.ANYWHERE)));
		}

		List<EnrolleePayment> list = criteria.list();

		List<EnrolleePayment> result = new ArrayList<EnrolleePayment>();

		if (beginPeriod != null && !beginPeriod.isEmpty() && endPeriod != null
				&& !endPeriod.isEmpty()) {
			for (EnrolleePayment enrolleePayment : list) {
				String dateActivation = enrolleePayment.getDateActivation();
				String[] split = dateActivation.split(" ");
				String date = split[0];
				java.util.Date dateActive;
				try {
					dateActive = new SimpleDateFormat("dd-mm-yyyy",
							Locale.ENGLISH).parse(date);

					java.util.Date beginDate = new SimpleDateFormat(
							"yyyy-mm-dd", Locale.ENGLISH).parse(beginPeriod);
					java.util.Date endDate = new SimpleDateFormat("yyyy-mm-dd",
							Locale.ENGLISH).parse(beginPeriod);

					if (dateActive.after(beginDate)
							&& dateActive.before(endDate)
							|| dateActive.equals(beginDate)
							|| dateActive.equals(endDate)) {
						result.add(enrolleePayment);
					}
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
		}

		double sum = 0;
		for (EnrolleePayment enrolleePayment : result) {
			sum += enrolleePayment.getSum();
		}

		return sum;
	}

}
